<?php

class InvoiceController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			/*array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),*/
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('index','view','create','update','delete','viewPDF', 'close','viewInvoice','purchase'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	public function actionClose($id){
		Invoice::model()->updateByPk($id,array('generate'=>1));
		$this->redirect(array('view','id'=>$id));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$modelInvoice=$this->loadModel($id);
		$modelQuotation=QuotationOrderHeader::model()->find("PO_ref=:PO_ref",
															 array(
															 	'PO_ref'=>$modelInvoice->PO_reference,
															));
		$this->render('view',array(
			'modelInvoice'=>$modelInvoice,
			'modelQuotation'=>$modelQuotation,
		));
	}

	public function actionViewPDF($id){
		# mPDF
        $mPDF1 = Yii::app()->ePdf->mpdf();
		$modelInvoice = $this->loadModel($id);
		$modelQuotation=QuotationOrderHeader::model()->find("PO_ref=:PO_ref",
															 array(
															 	'PO_ref'=>$modelInvoice->PO_reference,
															));
		$modelCustomer=Customer::model()->find('id=:id',array(':id'=>$modelQuotation->customer));
		$modelDetail=QuotationOrderDetail::model()->findAll('quotation_no=:quotation_no',
														array(':quotation_no'=>$modelQuotation->quotation_no));
		foreach ($modelDetail as $value) {
			$modelProduct[]=Product::model()->find('product_pn=:product_pn',array(':product_pn'=>$value->product_pn));
		}

		$this->render('invoice',array(
							'modelInvoice'=>$modelInvoice,
							'modelQuotation'=>$modelQuotation,
							'modelCustomer'=>$modelCustomer,
							'modelDetail'=>$modelDetail,
							'modelProduct'=>$modelProduct
							));

	}

	public function actionPurchase(){

		$model=QuotationOrderHeader::model()->findAll('generate=:generate',array('generate'=>1));
		$result = array();
	    $result["total"] = count($model);
	    $rows = array();
	    foreach ($model as $row) {
	        array_push($rows, $row->getAttributes(array(
	            'quotation_no',
	            'PO_ref',
	            )));
	    }
	    $result["rows"] = $rows;
	    echo CJSON::encode($result);
	}

	public function getLastSO(){

		Counter::editCounter();

		$model=Invoice::model()->findAll('1=1 order by invoice_no desc');
		
		$lastId= substr($model[0]->invoice_no,2);
		$counter= Yii::app()->session['counter'];
		$lastId=((int)$lastId+$counter['userLogin']);

        
		$temp_no='';
		if($lastId<10)
			$temp_no='SO000'.$lastId;
		else if($lastId<100)
			$temp_no='SO00'.$lastId;
		else if($lastId<1000)
			$temp_no='SO0'.$lastId;
		else if($lastId>=1000)
			$temp_no=$lastId;

		return $temp_no;
        }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Invoice;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Invoice']))
		{
			$model->attributes=$_POST['Invoice'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->invoice_no));
		}

		$lastSO=$this->getLastSO();
		$tempValue['lastSO']=$lastSO;
		$tempValue['po_no']='';

		$this->render('create',array(
			'model'=>$model,
			'tempValue'=>$tempValue,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$tempValue['lastSO']=$model->invoice_no;
		$tempValue['po_no']=$model->PO_reference;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Invoice']))
		{
			$model->attributes=$_POST['Invoice'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->invoice_no));
		}

		$this->render('update',array(
			'model'=>$model,
			'tempValue'=>$tempValue,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		/*$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));*/

		Invoice::model()->updateByPk($id,array('status_delete'=>'DELETED'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		Yii::app()->session['controller']='invoice';
		Yii::app()->session['po_no']='';
		$created_by=Yii::app()->session['id'];

		if(isset(Yii::app()->session['adminUser']))
			$model=Invoice::model()->findAll('status_delete=:delete',array('delete'=>'-'));
		else
			$model=Invoice::model()->findAll('created_by=:created_by and t.status_delete="-"',array('created_by'=>$created_by));

		 $this->render('admin',array(
			'model'=>$model,
		 )); 
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		/*$model=new Invoice('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Invoice']))
			$model->attributes=$_GET['Invoice'];

		$this->render('admin',array(
			'model'=>$model,
		));*/
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Invoice the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Invoice::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Invoice $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='invoice-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
